package com.tanhua.sso.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.*;
import com.tanhua.autoconfig.tmplate.HuanXinTemplate;
import com.tanhua.config.UserHolder;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.result.Result;
import com.tanhua.sso.pojo.*;
import com.tanhua.sso.utils.CommentType;
import com.tanhua.sso.utils.RelativeDateFormat;
import com.tanhua.sso.vo.AnnouncementVo;
import com.tanhua.sso.vo.ContactVo;
import com.tanhua.sso.vo.Likes;
import com.tanhua.sso.vo.UserInfoVo;
import com.tanhua.util.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MessagesService {

    @DubboReference
    private UserService userService;

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private FriendServiceApi friendServiceApi;

    @DubboReference
    private CommentsServiceApi commentsServiceApi;

    @DubboReference
    private AnnouncementsServiceApi announcementsServiceApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    //查询环信用户详细信息
    public UserInfoVo findUserHuanXin(String huanxinId) {
        //环信用户id查询
        User user =userService.selectByHuanXinId(huanxinId);
        UserInfo userInfo = userInfoService.selectUser(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友
    public void contacts(Long userId) {
        //获取当前用户id
        Long nowId = UserHolder.getUserId();
        //环信添加好友
        Boolean flag = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + nowId);
        if (!flag){
            throw new CustomException("环信好友添加失败");
        }
        //先判断数据库是否有添加好友的信息
        boolean exist=friendServiceApi.selectFriend(nowId,userId);
        if (exist){
            throw new CustomException("已经是好友了,不用添加了");
        }else {
            //添加好友
            Friend friend=new Friend();
            friend.setFriendId(userId);
            friend.setUserId(nowId);
            friend.setCreated(System.currentTimeMillis());
            friendServiceApi.addFriend(friend);
        }
        //先判断数据库是否有添加好友的信息
        boolean otherExist=friendServiceApi.selectFriend(userId,nowId);
        if (otherExist){
            throw new CustomException("已经是好友了,不用添加了");
        }else {
            //添加好友
            Friend friend=new Friend();
            friend.setFriendId(nowId);
            friend.setUserId(userId);
            friend.setCreated(System.currentTimeMillis());
            friendServiceApi.addFriend(friend);
        }
    }

    /*分页条件查询好友列表*/
    public Result getContacts(Integer page, Integer pagesize, String keyword) {
        //获取当前用户id
        Long nowId = UserHolder.getUserId();
        //获取所有好友的id
        List<Long> listId=friendServiceApi.myFriendIds(nowId);
        //分页条件查询好友信息
        Page<UserInfo> page1=userInfoService.page(page,pagesize,keyword,listId);
        //获取查询信息
        List<UserInfo> records = page1.getRecords();
        if (ObjectUtil.isEmpty(records)){
            throw new CustomException("差无信息");
        }
        //封装
        List<ContactVo> contactVoList=new ArrayList<>();
        for (UserInfo record : records) {
            ContactVo vo = ContactVo.init(record);
            contactVoList.add(vo);
        }

        Integer count = Convert.toInt(page1.getTotal());

        Integer pages=1;
        int i=(count/pagesize)-1;
        if (i>1){
            page=i;
        }
        return new Result(count,pagesize,pages,page,contactVoList);
    }


    //点赞列表
    public Result likes(Integer page, Integer pagesize,Integer type) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();

        List<Comment> commentList=commentsServiceApi.findType(userId,type,page,pagesize);
        if (ObjectUtil.isEmpty(commentList)){
            throw new CustomException("暂无信息");
        }
        List<Likes> likes=new ArrayList<>();
        for (Comment comment : commentList) {
            Likes newLikes=new Likes();
            //设置id
            newLikes.setId(comment.getId().toHexString());
            //设置时间
            newLikes.setCreateDate(RelativeDateFormat.format(new Date(comment.getCreated())));
            Long commentUserId = comment.getPublishUserId();
            UserInfo userInfo = userInfoService.selectUser(commentUserId);
            //设置头像
            newLikes.setAvatar(userInfo.getAvatar());
            //设置呢称
            newLikes.setNickname(userInfo.getNickname());
            likes.add(newLikes);
        }
        //总条数
        Integer count=commentList.size();
        //总页数
        Integer pages=1;
        int i=(count/pagesize)-1;
        if (i>1){
            page=i;
        }
        return new Result(count,pagesize,pages,page,likes);
    }


    //公告列表
    public Result getAnnouncements(Integer page, Integer pagesize) {
        Page<Announcement> announcementPage=announcementsServiceApi.getAnnouncements(page,pagesize);
        List<Announcement> records = announcementPage.getRecords();
        if (ObjectUtil.isEmpty(records)){
            throw new CustomException("无公告");
        }
        List<AnnouncementVo> announcementVoList=new ArrayList<>();
        for (Announcement record : records) {
            AnnouncementVo announcementVo=new AnnouncementVo();
            announcementVo.setCreateDate(RelativeDateFormat.format(record.getCreated()));
            announcementVo.setId(Convert.toStr(record.getId()));
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVoList.add(announcementVo);
        }
        Integer count=Convert.toInt(announcementPage.getTotal());
        //总页数
        Integer pages=1;
        int i=(count/pagesize)-1;
        if (i>1){
            page=i;
        }
        return new Result(Convert.toInt(announcementPage.getTotal()),pagesize,pages,page,announcementVoList);
    }

    /*删除好友*/
    public void deleteFriend(Long likeUserId) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //删除环信好友
        Boolean aBoolean = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + likeUserId);
        if (!aBoolean){
            throw new CustomException("删除失败");
        }
        //删除friend表中数据
        friendServiceApi.deleteFriend(userId,likeUserId);
    }
}
